package taxi_map.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

public class WaitingUser implements Runnable {
	static final int RUNNING = 0;
	static final int SUSPENDED = 1;
	static final int STOPPED = 1;
	
	Thread th;
	Map<String,Object> map;
	HttpServletResponse response;
	
	WaitingUser(HttpServletResponse response){
		th = new Thread(this);
		this.response = response;
	}
	
	public void join() throws InterruptedException {
		// TODO Auto-generated method stub
		th.join();
	}

	public void start(){
		th.start();
	}
	
	public synchronized void sendUserRequest(Map<String,Object> map){
		this.map = map;
		notify();
	}
	
	public synchronized void waitForUserRequest(){
		try {
			wait();
		} catch (InterruptedException e) {}
	}
	
	@Override
	public void run() {	
		PrintWriter out = null;
		waitForUserRequest();
		JSONObject jobj = null; 
		try {
			jobj = new JSONObject(map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		response.setContentType("text/html;charset=utf-8");
		response.setHeader("cache-control", "no-cache");
		try {
			out = response.getWriter();
			out.print(jobj);
			out.flush();
			
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
}